import Vue from 'vue'
import axios from 'axios'
import store from '../store'
import router from '../router'

axios.interceptors.response.use(
    response => {
        return response
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token信息并跳转到登录页面
                    router.replace({
                        path: '/'
                    })
                    location.reload()
            }
        }
    }
)

export default class http {
    static async request(method, url, data, loading = true) {
        const param = {
            url: url,
            method: method,
            data: data
        }
        console.info(`[http]request url=${url}`)
        const userToken = store.state.access_token;
        if (data.headerData == 1) {
            axios.defaults.headers.common = {
                'Content-Type': 'multipart/form-data',
                'Authorization': 'Bearer ' + userToken
            }
        } else {
            axios.defaults.headers.common = {
                'Content-Type': 'application/json; charset=UTF-8',
                'Authorization': 'Bearer ' + userToken
            }
        }
        const res = await this._request(param)
        if (this.isSuccess(res)) {
            return res.data
        } else {
            Vue.prototype.$message({
                showClose: true,
                type: "error",
                message: res.data.msg
            });
            return res.data
        }
    }
    /**
     * 判断请求是否成功
     */
    static isSuccess(res) {
        const dataCode = res.data.code
        if (dataCode != 0) {
            return true
        } else {
            return false
        }

    }

    static async _request(param) {
        let data = param.data
        if (param.method === 'GET') {
            return axios.get(param.url, {
                params: data
            })
        }
        return axios(Object.assign({}, param))
    }

    static get(url, data, loading = true) {
        return this.request('GET', url, data, loading)
    }

    static put(url, data, loading = true) {
        return this.request('PUT', url, data, loading)
    }

    static post(url, data, loading = true) {
        return this.request('POST', url, data, loading)
    }
    static delete(url, data, loading = true) {
        return this.request('DELETE', url, data, loading)
    }

}
